#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
|===== Conference Bot Plugin ============
|= Information Commands
|===== By: ==============================
|= Patrick Kennedy
|===== Current Version: =================
|= 1.0
|===== Description: =========================================
|= Various commands designed to display information about the bot.
|===== Additional Comments: =================================
|= 
|============================================================"""
from ini import core
from utils import *

def init(bot):
	bot.addCommand("help", cmd_help)
	bot.addMuteCommand("help", cmd_help)
	bot.addCommand("names",cmd_names)
	bot.addCommand("w",cmd_names)
	bot.addCommand("whois",cmd_whois)
	bot.addCommand("!",cmd_status)

def unload(bot):
	bot.removeCommand(["help", "names", "w", "whois"])

def cmd_help(bot,user,args):
	"""Display this help message.
Usage: )help [command]
Display detailed information about a command.

Bracket meanings:
* [] - Anything enclosed in these is optional.
Ex: The usage above works with or without a command name.
* <> - Words inside these are require.
Usually are explained or self-explanatory."""
	
	if args:
		args = args.split(" ",1)[0]
		if args in bot.commands:
			bot.msg(user, bot.commands[args].__doc__)
		elif args in bot.modcommands:
			bot.msg(user, bot.modcommands[args].__doc__)
		elif args in bot.admincommands:
			bot.msg(user, bot.admincommands[args].__doc__)
		else:
			bot.error(user, "There is no command %s. Please check your spelling." % args)
	else:
		reply = """Commands prefixes: %s
		
For more information about a command type )help <command name>.

----

""" % (bot.config.system.commandprefix)
		if ismuted(user):
			for i in sortdict(bot.mutecommands):
				try:
					reply = reply + "%s | %s\n" % (i, bot.mutecommands[i].__doc__.split("\n")[0])
				except:
					continue
		else:
			for i in sortdict(bot.commands):
				try:
					reply = reply + "%s | %s\n" % (i, bot.commands[i].__doc__.split("\n")[0])
				except:
					continue
			if ismod(user) or isadmin(user):
				reply = reply + "\nModerator commands:\n"
				for i in sortdict(bot.modcommands):
					try:
						reply = reply + "%s | %s\n" % (i, bot.modcommands[i].__doc__.split("\n")[0])
					except:
						continue
			if isadmin(user):
				reply = reply + "\nAdmin commands:\n"
				for i in sortdict(bot.admincommands):
					try:
						reply = reply + "%s | %s\n" % (i, bot.admincommands[i].__doc__.split("\n")[0])
					except:
						continue
		bot.msg(user,reply)

def cmd_names(bot, user, args):
	"""List every user in the bot.
Key:
* '@' - Admin
* '%' - Mod
* '-' - Away
* '!' - Busy
* '#' - Banned"""

	names = []
	admins = []
	online = []
	offline = []
	away = []
	idle = []
	busy = []
	
	for i in bot.getRoster():
		name = getdisplayname(i)
		if name == core.required.username:
			continue
		jidStatus = bot.getJidStatus(i).items()
		if jidStatus != []:
			for who,(status,display) in jidStatus:
				if '@' not in unicode(who):
					continue
				if has_userflag(who, "status", 'banned'):
						name = "#%s" % name
						continue
						
				if [(unicode(jid),message) for (jid,(status,message)) in jidStatus if status in ["online","chat"]]:
					if isadmin(who):
						name = "@%s" % name
						admins.append(name)
					elif ismod(who):
						name = "%"+"%s" % name
						admins.append(name)
					if has_userflag(who, "status", 'away'):
						name = "-%s" % name
						away.append(name)
					else:
						online.append(name)
					break	
				
				#Anyone not "available".
				elif [(unicode(jid),message) for (jid,(status,message)) in jidStatus if status in [u"away",u"dnd",u"xa"]]:
					if status in [u"away",u"xa"]:
						name = "-%s" % name
						idle.append(name)
					elif status == u"dnd":
						name = "!%s" % name
						busy.append(name)
					break
		else:
			offline.append('(%s)' % name)
						
	bot.sys(user, formatmessage(
							user,
							"names",
							'Users:\n\
							Offline: (%(d_off)d)\n%(off)s\n\n\
							Idle: (%(d_idle)d)\n%(idle)s\n\n\
							Away: (%(d_away)d)\n%(away)s\n\n\
							Busy: (%(d_busy)d)\n%(busy)s\n\n\
							Available: (%(d_on)d)\n%(on)s\n\n\
							Total: (%(d_total)d)',
							d_off = len(offline), 
							off = " ".join(offline), 
							d_idle = len(idle), 
							idle = " ".join(idle),
							d_away = len(away),  
							away = " ".join(away), 
							d_busy = len(busy), 
							busy = " ".join(busy), 
							d_on = len(online), 
							on = " ".join(online), 
							d_total = len(online + offline + idle + away + busy), 
							total = (online + busy + idle + away + offline)
							))


def cmd_status(bot, user, args):
	"""List every user in the bot."""

	names = []
	admins = []
	online = []
	offline = []
	away = []
	idle = []
	busy = []

	for i in bot.getRoster():
		name = getdisplayname(i)
		if name == core.required.username:
			continue
		jidStatus = bot.getJidStatus(i).items()
		if jidStatus != []:
			for who,(status,display) in jidStatus:
				if '@' not in unicode(who):
					continue
				#name = name.ljust(15)

				if [(unicode(jid),message) for (jid,(status,message)) in jidStatus if status in ["online","chat"]]:
					if has_userflag(who, "status", 'away'):
						name = "%s - away" % name
						away.append(name)
					else:
						name = "%s - online" % name
						online.append(name)
					break

				#Anyone not "available".
				elif [(unicode(jid),message) for (jid,(status,message)) in jidStatus if status in [u"away",u"dnd",u"xa"]]:
					if status in [u"away",u"xa"]:
						name = "%s - idle" % name
						idle.append(name)
					elif status == u"dnd":
						name = "%s - busy" % name
						busy.append(name)
					break
		else:
			name = "%s - offline" % name
			offline.append('%s' % name)

	online.sort(key=lambda s: s.lower())
	idle.sort(key=lambda s: s.lower())
	away.sort(key=lambda s: s.lower())
	busy.sort(key=lambda s: s.lower())
	offline.sort(key=lambda s: s.lower())

	bot.sys(user, formatmessage(
							user,
							"names",
							'Users:\n%(on)s\n%(idle)s\n%(away)s\n%(busy)s\n%(off)s\n',
							on = "\n".join(online),
							idle = "\n".join(idle),
							away = "\n".join(away),
							busy = "\n".join(busy),
							off = "\n".join(offline)
							))






def cmd_whois(bot, user, args):
	"""Displays a user's info.
Usage: )whois <username>"""
	if not args:
		bot.msg(user,cmd_whois.__doc__)
		return
		
	i = getjid(args.lower())
	try:
		for who,(status,display) in bot.getJidStatus(i).items():
			bot.msg(user, "Who:\n%s\n\n Status:\n%s\n\n Display:\n%s\n----------" % (who, status, display))
	except:
		bot.msg(user,"That user doesn't exist.")
